﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;

namespace MyyntiLaskin
{
    public partial class MainWindow : Window
    {
        Myynti myynti;

        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = myynti;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            pathTextBox.Text = Properties.Settings.Default.DefaultPath;
        }

        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "XML files (*.xml)|*.xml";
            ofd.InitialDirectory = Environment.CurrentDirectory;

            if (ofd.ShowDialog() == true)
            {
                pathTextBox.Text = ofd.FileName;

                Properties.Settings.Default.DefaultPath = ofd.FileName;
                Properties.Settings.Default.Save();
            }
        }

        private void ProcessButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(pathTextBox.Text))
                return;

            try
            {
                myynti = Myynti.LoadFromXml(pathTextBox.Text);

                this.DataContext = myynti;

                statusTextBlock.Text = string.Format(
                    "{0} asiakasta, myynnit yhteensä {1}",
                    myynti.Asiakkaat.Count,
                    myynti.Asiakkaat.Sum(s => s.MyynnitYhteensa));
            }
            catch (System.IO.IOException)
            {
                statusTextBlock.Text = "tiedoston avaaminen epäonnistui";
            }
            catch (System.InvalidOperationException ex)
            {
                statusTextBlock.Text = ex.InnerException.Message;
            }
            catch (Exception ex)
            {
                statusTextBlock.Text = ex.ToString();
            }
        }
    }
}
